
import {
	userIsLogin,
	getWeChartSmallProgramLoginInfo,
	dcH5WechatLogin, 
	searchUserInfoById,
	getBusinessInfo
 } from '@/tools/request/api.js'
 import JSONBig from 'json-bigint';
 
 
 

export default {
	namespaced: true,
	state: () => ({
		userId: uni.getStorageSync('__ddminiUserInfo').id || '',
		accessToken: uni.getStorageSync('__ddminiUserInfo').accessToken || '',
		userServiceToken: uni.getStorageSync('__ddminiUserInfo').userServiceToken || '',
		adminId: uni.getStorageSync('__ddminiUserInfo').adminId || '',
		adminUserInfo: uni.getStorageSync('__ddminiUserInfo') || {},
		openId: uni.getStorageSync('__ddminiUserOpenid') || '',
		addressList: uni.getStorageSync('__userAddressList') || [],
		currentAddress: {},
		userInfo: {},
		isDone: false, // 是否登录完成，以及获取到了首页所需要的所有参数，避免因请求时机问题造成首页数据获取失败。
		callList: [],
	}),
	mutations: {
		// 设置登录用户信息
		SET_ADMIN_USER_INFO (state, value) {
			state.userId = value.id;
			state.accessToken = value.accessToken;
			state.userServiceToken = value.userServiceToken;
			state.adminId = value.adminId;
			state.adminUserInfo = value;
			state.openId = JSON.parse(value.associatedAccounJson).wechat_open_id;
			uni.setStorageSync('__ddminiUserInfo', value);
			uni.setStorageSync('__ddminiUserOpenid', state.openId);
			state.isDone = true;
			this.commit('app_store/IS_APP_DONE');
		},
		// 设置用户收货地址
		SET_USER_ADDRESS (state, value) {
			if (value) {
				let originList = JSON.parse(value);
				originList.sort((a, b) => {
					if (a.default) {
						return -1;
					}
				})
				value = originList;
			} else {
				value = [];
			}
			state.addressList = value;
			uni.setStorageSync('__userAddressList', value);
		},
		// 设置用户当前选择的地址
		SET_CURRENT_ADDRESS (state, value) {
			state.currentAddress = value;
		},
		// 设置用户个人信息
		SET_USER_INFO (state, value) {
			state.userInfo = value;
		},
		// 是否初始化完成
		IS_APP_DONE (state, call) {
			if (call) {
				state.callList.push(call);
			}
			if (!state.isDone) return;
			if (!state.callList.length) return;
			state.callList.forEach((item) => {
				item();
			})
			state.callList = [];
		}
	},
	actions: {
		initApp ({dispatch, state}) {
			dispatch('checkLogin');
		},
		async checkLogin ({dispatch, commit, state, rootState}) {
			if (state.accessToken) {
				let result = await userIsLogin();
				if (result.code != 200) return $showMsg();
				if (result.body.isLogin) {
					state.isDone = true;
					commit('IS_APP_DONE');
					return;
				}
				uni.removeStorageSync('__ddminiUserInfo');
				dispatch('login');
			} else {
				dispatch('login');
			}
		},
		async login ({commit, dispatch, state, rootState}) {
			uni.login({
				provider: 'weixin',
			    success: async (wes) => {
					let loginInfo = await getWeChartSmallProgramLoginInfo({code: wes.code});
					if (loginInfo.code != 200) return uni.$showMsg();
					let identification = loginInfo.body.openid;
					let user = {
						identification: identification,
					};
					let postData = `wechatServerJSON=${JSON.stringify(user)}`;
					let loginRes = await dcH5WechatLogin(postData);
					if (loginRes.code != 200) return uni.$showMsg();
					let result = loginRes.body;
					commit('SET_ADMIN_USER_INFO', result);
					commit('SET_USER_ADDRESS', result.receiveAddressJson);
			    }
			});
		},
		async getUserInfo ({commit, state}) {
			if (state.userId) {
				let res = await searchUserInfoById({userId: state.userId});
				if(res.code != 200) return uni.$showMsg();
				commit('SET_USER_ADDRESS', res.body.receiveAddressJson);
				commit('SET_USER_INFO', res.body);
				uni.stopPullDownRefresh();
			}
		},
	},
	getters: {
		addressList (state) {
			return state.addressList;
		}
	},
}
